<template>
  <div class="home_content">
    <a-alert banner center class="home_space" :show-icon="false" style="{{ color: '#fff' }}">
      <a><span v-html="vHtmlDom"></span></a>
      <!-- <a ><span><b>最好用的批量下载工具👏</b><span class="ac-navbar-global-notice-desc"></span></span><b> 查看更多 <svg
            viewBox="0 0 48 48" fill="none" xmlns="http://www.w3.org/2000/svg" stroke="currentColor"
            class="arco-icon arco-icon-right" stroke-width="4" stroke-linecap="butt" stroke-linejoin="miter">
            <path d="m16 39.513 15.556-15.557L16 8.4"></path>
          </svg></b></a> -->
    </a-alert>
    <a-form :model="form" ref="formRef">
      <a-form-item field="link" no-style>
        <a-textarea class="form_item" placeholder="链接: https://pan.baidu.com/s/1QApWnCkZJcdt0ISsKlMEUg?pwd=94rx 提取码: 94rx 复制这段内容后打开百度网盘手机App，操作更方便哦 
                    --来自百度网盘超级会员v3的分享" v-model='textareValue' @input="hanldeChange" />
      </a-form-item>
      <a-form-item no-style class="form_item">
        <div class="home_content_form_box">
          <a-space>
            <a-button type="primary" @click="handleStart" :loading="startLoading">开始处理</a-button>
            <a-button type="primary" status="success" @click="handleDownload" :loading="downloadloading">打包下载</a-button>
            <a-button type="primary" status="danger" @click="handleReset">重置</a-button>
          </a-space>
          <a-input placeholder="请输入密码" style="width:120px" v-model="pwd" disabled />
        </div>

      </a-form-item>
    </a-form>
    <div class="home_content_files">
      <h2>处理结果</h2>
      <a-divider />
      <a-table row-key="name" :data="tableData" :bordered=false :scrollbar=false :row-selection="rowSelection"
        :pagination="false" :loading="loading" :load-more="loadMore" :indent="24" :tree-data="true" show-empty-tree
        v-model:selectedKeys="selectedKeys">
        <!-- 自定义单元格模板，根据是否有子节点显示不同的图标 -->
        <!-- <template v-slot:icon="{ record }">
                <a-icon
                  :type="record.isLeaf ? 'folder' : 'file'"
                />
              </template> -->
        <template #columns>
          <!-- 定义全选的列 -->

          <a-table-column title="文件名" key="name" align="left">
            <template #cell="{ record }">
              <!-- 自定义 Name 列的渲染，例如添加前缀 -->
              <div class="table_td">
                <a-image :src="file_pg" width="24" />
                <span> {{ record.name }}</span>
              </div>

            </template>
          </a-table-column>
        </template>

      </a-table>
    </div>
    <!-- <a-modal :visible="kamiVisble" title="输入卡密" :footer='null' @cancel="handleCancel">
      <a-form :model="form_card" @submit="handleSubmit">
        <a-space direction="vertical" fill :size="24">
          <a-form-item field="cardNumber" label="" no-style>
            <a-input v-model="form_card.cardNumber" placeholder="请输入卡密" width="200" />
          </a-form-item>
          <a-form-item no-style>
            <a-button html-type="submit" type="primary" long>Submit</a-button>
          </a-form-item>
        </a-space>

      </a-form>
    </a-modal> -->
    <PscgoDialog :visible="kamiVisble" v-on:update:visible="handleSubmit" v-on:update:close="handleCancel" />
  </div>
</template>

<script>
export default {
  name: 'PscgoHome',
  components: {
    // HelloWorld
  }
}
</script>
<script setup>
import { onActivated, reactive, ref, onDeactivated, computed, onMounted } from 'vue'
import file_pg from '@/assets/file.png'
import { getURLByParm, transformData, renameSubToChildren, findNodeByName } from '@/util/index.js'
import { Notification } from '@arco-design/web-vue';
import PscgoDialog from '@/components/PscgoDialog.vue'
import { useUserStore } from '@/store.js';
import { flattenStructure } from '@/util/flatTree';

const userStore = useUserStore();
const user = computed(() => userStore.userInfo);
const form = reactive({
  link: '',
});
const form_card = reactive({
  cardNumber: ''
})

let vHtmlDom = ref('')
const formRef = ref('')
// const selectedKeys = ref([]);
const selectedKeys = ref([]);

// 行选择配置
const rowSelection = reactive({
  type: 'checkbox',
  showCheckedAll: true,
  // onlyCurrent: false,
  checkStrictly: true
});

const textareValue = ref('')
const pwd = ref('')
const loading = ref(false)
const kamiVisble = ref(false)


let treeData = {};
// let treeMeta = {};
// let currentPath = [];
let tableData = ref([])
let urlMatch = ref('')
const startLoading = ref(false)
const downloadloading = ref(false);

onMounted(() => {
  // 获取banner信息
  getBannerConf()
})

// 获取banner配置
const getBannerConf = async () => {
  const res = await window?.electron?.getBannerConf()
  vHtmlDom.value = res
  //  console.log(res)
}

// 
const handleCancel = () => {
  kamiVisble.value = false;
}

// 输入卡密
const handleSubmit = async (data) => {
  // await window?.electron?.submitCard(data?.cardNumber);
  // localStorage.setItem('card_number', data?.cardNumber)
  // await sleep(3);
  kamiVisble.value = false
  handleDownload()
  // triggerStart()
}
// 开始处理 loading
const handleStart = async () => {
  try {
    const val = textareValue.value.trim();
    if (!val.includes('https://pan.baidu.com')) {
      Notification.warning('请输入正确的链接')
      startLoading.value = false;
      loading.value = false
      return
    }
    triggerStart()
    // const user_token = localStorage.getItem('card_number');

  } catch (e) { console.log(e) }


}

// 开始下载
const triggerStart = async () => {
  // transfer links 的逻辑
  startLoading.value = true;
  loading.value = true
  selectedKeys.value = []
  tableData.value = []
  try {
    if (pwd.value == '') {
      // const user_token = localStorage.getItem('card_number');
      const points = await window?.electron?.getPoints(user.value?.card_number);
      // const points = await window?.electron?.getPoints('51A7D4BB313D7D96');
      Notification.warning(`当前剩余点数: ${points}`)
    }
    const urlRegex = /(https:\/\/pan\.baidu\.com\/s\/[a-zA-Z0-9_-]+)\?pwd=([a-zA-Z0-9]{4})/;

    const val = textareValue.value.trim();
    const match = val.match(urlRegex);

    // 正则表达式用于匹配链接和提取码
    const regex = /https:\/\/pan\.baidu\.com\/s\/(\w+)[^\s]+ 提取码: (\w+)/;
    const matchSecond = val.match(regex);
    // let urlMatch = textareValue.value;

    //  let pwdMatch = textareValue.value;
    if (match) {
      urlMatch.value = match[1];
    } else {
      const urlRegex1 = /(https:\/\/pan\.baidu\.com\/s\/[a-zA-Z0-9_-]+)/;
      const extractCodeRegex = /提取码:\s*([a-zA-Z0-9]+)/;
      // 提取提取码
      const extractCodeMatch = val.match(extractCodeRegex);
      console.log('>>>', extractCodeMatch)
      const extractCode = extractCodeMatch ? extractCodeMatch[1] : null;
      const link = val.match(urlRegex1)[1];
      pwd.value = extractCode;
      urlMatch.value = link;
      // console.log('提取码:', 提取码);
      // console.log('提取码:', 提取码);
    }

    const data = await window?.electron?.ShareLinksTransfer(`${urlMatch.value}?pwd=${pwd.value}`, '');
    loading.value = false
    startLoading.value = false;
    if (data.errno == 10002) {
      // customAlert('没有卡密，请先添加卡密');
      Notification.warning('没有卡密，请先添加卡密')
      return;
    }
    if (data.errno == 20070) {
      Notification.warning('卡密错误，请重新输入')
      return;
    }
    if (data.errno == 20071) {
      Notification.warning('卡密次数不足')
      return;
    }
    if (data.errno == 20072) {
      Notification.warning('卡密失效')
      return;
    }
    if (data.errno == 20017) {
      Notification.warning('未获取到可用账号，账号失效')
      return;
    }
    if (data.errno == 20015) {
      Notification.warning('未获取到可用账号')
      return;
    }
    if (data.errno == 20016) {
      Notification.warning('分享链接转存到网盘失败-4: 未知错误, 错误代码-32')
      return;
    }
    if (data.data.list === 0) {
      Notification.warning('没有可用的链接')
      return;
    }
    const res = [...data.data.list]?.map(v => ({
      ...v,
      name: v?.file_name,
      isLeaf: !v?.is_dir,
      // children: []
    }))
    res?.map(v => {
      return renameSubToChildren(v)
    })
    tableData.value = res
    Notification.success('获取文件列表成功')

    // data.data?.list?.forEach(item => parseDirectory(item));

    //   console.log(data.data.list)
    treeData = transformData(data.data?.list);
    // console.log(data.data.list, treeData)
    //  navigateToPath(treeData, []);

  } catch (error) {
    startLoading.value = false;
    loading.value = false
    console.error('Error fetching file list:', error);
    Notification.error(`获取文件列表失败， ${error}`)
    return;
  } finally {
    startLoading.value = false;
    loading.value = false
    // loadingElement.style.display = 'none';
    // treeElement.style.display = 'block';
  }

}

// 开始下载
// 坐等后端接口
const handleDownload = async () => {
  if (user.value?.card_number) {
    form_card.cardNumber = user.value?.card_number
    downloadloading.value = true
    let selectedFiles = [];
    // console.log(selectedKeys.value, tableData)
    if (selectedKeys.value?.length === 0) {
      Notification.warning('请先勾选')
      downloadloading.value = false
      return
    }

    try {
      let query = {
        user_token: user.value.card_number,
        share_addr: `${urlMatch.value}?pwd=${pwd.value}`,
      }

      let fsid_list = selectedKeys.value?.map(v => {
        const replacedata = [...tableData.value]
        console.log(replacedata)
        const cc = findNodeByName(v, replacedata) // 数组
        const fsid_list = [...cc]?.map(v => v.fs_id)?.filter(v => !v)
        return cc[0]?.fs_id
      })?.filter(v => !!v)
      const file_list = selectedKeys.value?.map(v => {
        const replacedata = [...tableData.value]
        const cc = findNodeByName(v, replacedata) // 数组
        const fsid_list = [...cc]?.map(v => v.fs_id)?.filter(v => !v)
        console.log(cc)
        return {
          fsid: cc[0]?.fs_id,
          fname: cc[0]?.name || '',
          path: cc[0]?.path || ''
        }
      })?.filter(v => !!v)
      
      // 这里需要调用勾选转存接口
      console.log('>>>>', fsid_list, file_list)
      query = {
        ...query,
        file_list: file_list
        // fsid_list: fsid_list
      }
      console.log(query)
      // const demoQuery = {
      //   ...query,
      //   fsid_list: [6634319194]
      // }
      // const datares = await window?.electron?.TransformShareLinks(demoQuery)
      const datares = await window?.electron?.TransformShareLinks(query)
      const translist = datares?.data.list
      // 这里是不是要接触所有的link
      console.log('>>>>', datares)
      selectedFiles = flattenStructure(translist)
      // selectedFiles = translist?.map(v => ({
      //   id: Number(v.id),
      //   path: v?.name,
      //   buid: v.buid
      // }))
      console.log(selectedFiles)
      downloadloading.value = false
      // 勾选的文件列表
      await DownloadpackageFiles(selectedFiles)

    } catch (e) {
      downloadloading.value = false;
      Notification.error('下载失败了')
      console.log(e)
    }

  } else {
    kamiVisble.value = true
  }

}

// 开始打包下载
async function DownloadpackageFiles(links) {
  if (!links) return;
  // console.log('>>>>',tableData.value);
  let data = [...tableData.value];
  data = transformData(data);
  // console.log(data);

  // [...data]?.map(item => parseDirectory(item));
  // tableData.value  = data
  // console.log('下载',treeMeta, treeData);
  // console.log('TreeMeta:', treeMeta, treeData);
  // await window?.electron?.SetTreeMeta(treeMeta);
  await window?.electron?.SetTreeData(treeData);

  // let pswd = user.value.card_number
  // if (pswd == '') {
  //   const user_token = await window?.electron?.showCardInputDialog();
  //   pswd = user_token;
  //   const points = await window?.electron?.getPoints(user.value.card_number);
  //   // 这里要存储卡密的信息到详情页面
  //   // document.getElementById('pswd-description').innerText = `当前剩余点数: ${points}`;
  // }
  await window?.Electron?.getPoints(user.value.card_number);
  //  await window?.electron?.getPoints('51A7D4BB313D7D96');



  const res = await window?.electron?.DownloadFiles(links, user.value.card_number);
  // const res = await window?.electron?.DownloadFiles(demolinks, user.value.card_number);
  Notification.success('开始打包下载');
  downloadloading.value = false
  return res
}
// 获取二级数据
const loadMore = async (record, done) => {
  // console.log(record, done)
  if (record.is_dir) {
    // 开始预览数据
    const params = {
      dir: record?.path
    }
    const data = await window?.electron?.ShareLinksTransfer(`${urlMatch.value}?pwd=${pwd.value}`, '', params);
    const res = [...data.data.list]?.map(v => ({
      ...v,
      name: v?.file_name,
      isLeaf: !v?.is_dir
    }))
    res?.map(v => {
      return renameSubToChildren(v)
    })
    const aa = [...tableData.value]
    const currentData = findNodeByName(record.name, aa)
    // console.log(currentData)
    currentData[0].children = res // 
    // console.log('aa>>>',aa)
    tableData.value = aa
    // console.log('>>>>',tableData.value)
    // console.log(currentData, tableData)
    // tableData?.find(v => v.name === record)

    window.setTimeout(() => {
      done(res)
    }, 500)
  }

  // if(record.isLeaf) {


  //   // 新的数据插入tableData
  // }
}

// 重置
const handleReset = () => {
  textareValue.value = ''
  pwd.value = ''
  selectedKeys.value = []
  tableData.value = []
}


// 输入内容解析密码
const hanldeChange = (val) => {
  console.log(val)
  const urlRegex = /(https:\/\/pan\.baidu\.com\/s\/[a-zA-Z0-9_-]+)\?pwd=([a-zA-Z0-9]{4})/;
  const match = val.match(urlRegex);
  // console.log('>>>>',match);
  if (match) {
    const pwdVal = getURLByParm(match[0], 'pwd')
    pwdVal && (pwd.value = pwdVal)
  }

}

onActivated(() => {
  console.log('activate')
})
onDeactivated(() => {
  console.log('注销')
})

// function parseDirectory(directory, name = '') {
//   try {
//     if (!treeMeta[name]) {
//       treeMeta[name] = [];
//     }
//     if (directory.is_dir) {
//       directory?.children?.forEach(sub => parseDirectory(sub, directory.name));
//       treeMeta[name] = treeMeta[name].concat(treeMeta[directory.name])
//     } else {
//       treeMeta[name].push({
//         path: directory.name,
//         buid: directory.buid,
//         id: Number(directory.id)

//       });
//     }
//   } catch (error) {
//     console.log(error);
//   }
// }



</script>

<style scoped>
.home_content_form_box {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.home_space {
  margin-bottom: 20px;
  background: #3491fa;
  color: #fff;

}

.arco-alert-info .arco-alert-content {
  color: #fff;
}

.home_content :deep(.arco-alert-info .arco-alert-content) {
  color: #fff;
}

.form_item {
  margin-bottom: 20px;
}

.home_content_files {
  margin-top: 20px;
  text-align: left;
}

.table_td {
  display: flex;
  align-items: center;
}

.ac-navbar-global-notice-desc {
  font-size: 13px;
  margin-left: 36px;
  margin-right: 48px;
}

.home_content :deep(.arco-alert-info .arco-alert-content p) {
  margin-block-start: 0 !important;
  margin-block-end:  0 !important;
  margin: 0;
  padding: 0;
}
a, u {
  text-decoration: none !important;
}
</style>